<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input id="input"/><button id="btn">按钮</button>
</body>
<script>
let str = 'apple iPhone'
//replace第一个参数,字符串,替换第一个
// str = str.replace('p', '<span style="color: blue">p</span>')
//菜鸟教程
//https://www.runoob.com/regexp/regexp-syntax.html

// 静态替换
// str = str.replace(/p/gi, '<span style="color: blue">p</span>')
// console.log(str)

//实现动态替换
document.getElementById('btn').onclick = function(){
    var value = document.getElementById('input').value.trim()
    //错误写法,正则表达式简化写法不支持变量
    // str = str.replace(/value/gi, '<span style="color: blue">'+value+'</span>')
    //https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp
    var str2 = str.replace(new RegExp(value, 'gi'), '<span style="color: blue">'+value+'</span>')
    console.log(str2)
}
</script>
</html>